package org.ethan.practice;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;

/**
 * @ClassName: SquireImageView
 * @Desc:
 * @Author: ethan
 * @CreateDate: 2019/9/20 14:50
 */
public class SquireImageView extends View {

    private float widthFactor;
    private Context context;
    private int measuredWidth;
    private int measuredHeight;
    private Bitmap mTopBitmap;
    private Paint paint;

    public float getWidthFactor() {
        return widthFactor;
    }

    public void setWidthFactor(float widthFactor) {
        this.widthFactor = widthFactor;
        invalidate();
    }

    public SquireImageView(Context context) {
        this(context, null);
    }

    public SquireImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        TypedArray array = null;
        try {
            array = context.obtainStyledAttributes(attrs, R.styleable.SquireImageView);
            widthFactor = array.getFloat(R.styleable.SquireImageView_width_factor, 1f);
        } finally {
            if (array != null) {
                array.recycle();
            }
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measuredWidth = getMeasuredWidth();
        measuredHeight = getMeasuredHeight();
        mTopBitmap = getTopBitmap();
    }

    private Bitmap getTopBitmap() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap srcBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.dzq, options);
        return getNewBitmap(srcBitmap,measuredWidth,measuredHeight);
    }

    {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
       /* Rect rect = new Rect(0, 0, getWidth(), getHeight());
        canvas.drawBitmap(mTopBitmap, null, rect, null);*/

        canvas.clipRect(0, 0, getWidth() * widthFactor, getHeight());

        canvas.drawBitmap(mTopBitmap, 0, 0, paint);
        canvas.restore();
    }

    public Bitmap getNewBitmap(Bitmap bitmap, int destWidth ,int destHeight){
        // 获得图片的宽高.
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 计算缩放比例.
        float scaleWidth = ((float) destWidth) / width;
        float scaleHeight = ((float) destHeight) / height;
        // 取得想要缩放的matrix参数.
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片.
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        return newBitmap;
    }
}
